//
//  UserBean.m
//  IMTMonitor
//
//  Created by jun on 2019/12/31.
//  Copyright © 2019 itoc. All rights reserved.
//

#import "UserBean.h"

static UserBean *shareUser = nil;

@implementation UserBean

/**
 *  归档自动解码
 */
- (instancetype)initWithCoder:(NSCoder *)aDecoder{
    if (self = [super init]) {
        unsigned int outcunt = 0;
        Ivar *iva = class_copyIvarList([self class], &outcunt);
        for (int i = 0; i < outcunt; i++) {
            Ivar vars = iva[i];
            const char *chars = ivar_getName(vars);
            NSString *key = [NSString stringWithUTF8String:chars];
            id value = [aDecoder decodeObjectForKey:key];
            [self setValue:value forKey:key];
        }
    }
    return self;
}
/**
 *  归档自动编码
 */
- (void)encodeWithCoder:(NSCoder *)aCoder{
    unsigned int outcunt = 0;
    Ivar *iva = class_copyIvarList([self class], &outcunt);
    for (int i = 0; i < outcunt; i++) {
        Ivar vars = iva[i];
        const char *chars = ivar_getName(vars);
        NSString *key = [NSString stringWithUTF8String:chars];
        id value = [self valueForKey:key];
        [aCoder encodeObject:value forKey:key];
    }
}

+ (NSString *)homeDirectoryPath{
    NSString *pathDucment = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex: 0];
    NSString *createPath = [NSString stringWithFormat:@"%@/UserInformation",pathDucment];
    if (![[NSFileManager defaultManager] fileExistsAtPath:createPath]) {
        [[NSFileManager defaultManager] createDirectoryAtPath:createPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return [createPath stringByAppendingPathComponent:@"userInfor.data"];
}

+ (UserBean *)shareUser{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareUser = [[UserBean alloc] init];
        shareUser.loginStatus = NO;
        if ([[NSFileManager defaultManager] fileExistsAtPath:[self homeDirectoryPath]]) {
            shareUser = [NSKeyedUnarchiver unarchiveObjectWithFile:[self homeDirectoryPath]];
        }
    });
    return shareUser;
}

//检查用户是否登录
+ (BOOL)isLogin{
    return [UserBean shareUser].loginStatus;
}


//+ (void)saveUserData{
//    
//}

//清楚资料
+ (void)clearUserData{
    if ([[NSFileManager defaultManager] fileExistsAtPath:[UserBean homeDirectoryPath]]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:[UserBean homeDirectoryPath] error:&error];
        if (error) {
            NSLog(@"%@",error);
        }else{
            NSLog(@"清除成功");
            UserBean *model = [UserBean new];
            shareUser = model;
        }
    }
}

//保存用户信息
+ (void)uploadUserData:(NSDictionary *)data{
    shareUser = [UserBean yy_modelWithDictionary:data];
    shareUser.loginStatus = YES;
    [NSKeyedArchiver archiveRootObject:shareUser toFile:[UserBean homeDirectoryPath]];
}

@end
